--
-- Cambio en comentario para incorporar suma
--

COMMENT ON COLUMN public.prexartm.origen
    IS 'Origen de la actualizacion: P: Porcentual, +: Suma, M: Manual, F: desde Ficha, U: Ultima Compra, E: Proceso Especial';

DROP FUNCTION public.prexartm_agregar(integer, integer, integer, integer, character varying, numeric, character varying, boolean, character varying, character varying);

CREATE OR REPLACE FUNCTION public.prexartm_agregar(
	pidart integer,
	pidpre integer,
	pidcomm integer,
	pidpad integer,
	pdescripcion character varying,
	pvalor numeric,
	pcondicion character varying,
	pactualizoprexart boolean,
	porigen character varying,
	pcodambusracc character varying)
    RETURNS boolean
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE 
AS $BODY$
DECLARE
BEGIN
  IF not (pOrigen IN ('P','M','F','I','E','U', '+')) THEN
     raise exception 'Origen de actualizacion desconocido.';
  END IF;
  
  IF pActualizoPreXArt THEN 
	  IF NOT EXISTS (SELECT * FROM prexart WHERE idpre = pIdPre and idart = pIdArt) THEN 
		 INSERT INTO public.prexart (IdPre, IdArt, Valor, Origen, CodAmbUsrAcc) VALUES (pIdPre, pIdArt, pValor, 'I', pCodAmbUsrAcc);
	  ELSE
		 UPDATE public.prexart SET valor = pValor, origen = 'I', CodAmbUsrAcc = pCodAmbUsrAcc
		 WHERE idPre = pIdPre and idArt = pIdArt and (pCondicion is null or (pCondicion = '>' and pValor > valor));
	  END IF;
  END IF;											   
  IF EXISTS (SELECT * FROM ambcfg WHERE position('PreciosHistoricos' IN ini) > 0) THEN
     INSERT INTO public.prexartm (idart, idpre, idcomm, idpad, descripcion, valor, origen, CodAmbUsrAcc) VALUES
	                             (pIdArt, pIdPre, pIdComm, pIdPad, pDescripcion, pValor, pOrigen, pCodAmbUsrAcc);
  
  END IF;
  RETURN true;
END;
$BODY$;

ALTER FUNCTION public.prexartm_agregar(integer, integer, integer, integer, character varying, numeric, character varying, boolean, character varying, character varying)
    OWNER TO abacouser;

   
SELECT aaversion('512.00','511.00');
--    


